﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Meqs.Entity;
using Meqs.Entity.Parameters;
using Meqs.Logic;
using Meqs.Logic.Interface;
using Meqs.Utilities;

public partial class Moral_Teacher_ScoreInput_ClassMonthInput : ScoreInputBasePage
{
    private int _tableWidth;
    private DateTime _evalDate;
    protected static string ExcelFileName
    {
        get
        {
            string title = "{0}{1} 德育{2}报表";

            int schoolYear = SchoolYear;
            int term = Term;
            if (SchoolYear == -1 || Term == -1)
            {
                ISchoolInfoLogic schLogic = Container<ISchoolInfoLogic>.Instance;
                SchoolInfo sch = schLogic.FindBySchoolMark(SchoolMark);
                schoolYear = sch.SchoolYear;
                term = sch.SchoolTerm;
            }
            string termStr = term == 1 ? "上学期" : "下学期";
            return string.Format(title, Common.ConvertSchoolYear(schoolYear), termStr, Common.ReportDateType(3));
        }
    }

    protected static int EvalID 
    {
        get
        {
            int _evalId;
            if (int.TryParse(HttpContext.Current.Request["evalID"], out _evalId))
                return _evalId;
            return -1;
        }
    }

    protected static int Attribute
    {
        get
        {
            int _evalType;
            if (int.TryParse(HttpContext.Current.Request["attribute"], out _evalType))
                return _evalType;
            return -1;
        }
    }

    protected string ReportTitle
    {
        get
        {
            IList<ClassEvalHistory> chList = Container<IClassEvalHistoryLogic>.Instance.FindById(EvalID, SchoolMark);
            
            ClassEvalHistory ch;
            if (chList == null || chList.Count < 1)
                ch = new ClassEvalHistory();
            else
                ch = chList[0];

            string title = "{0}{1} {2}{3}报表";

            int schoolYear = SchoolYear;
            int term = Term;
            if (SchoolYear == -1 || Term == -1)
            {
                ISchoolInfoLogic schLogic = Container<ISchoolInfoLogic>.Instance;
                SchoolInfo sch = schLogic.FindBySchoolMark(SchoolMark);
                schoolYear = sch.SchoolYear;
                term = sch.SchoolTerm;
            }
            string termStr = term == 1 ? "上学期" : "下学期";
            return string.Format(title, Common.ConvertSchoolYear(schoolYear), termStr, ch.Caption, Common.ReportDateType(Attribute));
        }
    }

    protected string ReportSubTitle
    {
        get
        {
            string title = "月份：{0}";
            IClsInfoLogic clsLogic = Container<IClsInfoLogic>.Instance;
            ClsInfo cls = clsLogic.FindById(ClsID);
            return string.Format(title, _evalDate.Year + "年" + _evalDate.Month + "月");
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!DateTime.TryParse(Request["evalDate"], out _evalDate))
                _evalDate = DateTime.MinValue;

            BindHeadTable();
            BindBodyTable();
        }
    }

    /// <summary>
    /// 构造表格头
    /// </summary>
    protected void BindHeadTable()
    {
        _tableWidth = 0;
        IClassEvalTypeLogic ctLogic = Container<IClassEvalTypeLogic>.Instance;
        IClassEvalItemLogic ciLogic = Container<IClassEvalItemLogic>.Instance;

        IList<ClassEvalType> list;
        list = ctLogic.GetAllClassEvalType(EvalID, SchoolMark, SchoolYear, Term);

        TableRow row = new TableRow();
        TableRow subRow = new TableRow();
        row.Style["background-color"] = "#D4F1F9";
        subRow.Style["background-color"] = "#D4F1F9";

        TableCell cell = new TableCell();
        cell.Text = "序号";
        cell.RowSpan = 2;
        cell.CssClass = "FixedRowCol";
        cell.Style["width"] = "40px";
        row.Cells.Add(cell);
        _tableWidth += 40;

        cell = new TableCell();
        cell.Text = "班级";
        cell.RowSpan = 2;
        cell.CssClass = "FixedRowCol";
        cell.Style["width"] = "100px";
        row.Cells.Add(cell);
        _tableWidth += 100;

        int index = 0;
        foreach (ClassEvalType mt in list)
        {
            cell = new TableCell();
            cell.Text = mt.Caption;
            IList<ClassEvalItem> miList = ciLogic.GetItemByType(SchoolMark, mt.RID);
            cell.ColumnSpan = miList.Count;
            cell.CssClass = "FixedRow";
            cell.Style["width"] = (60 * miList.Count) + "px";
            _tableWidth += 60 * miList.Count;
            foreach (ClassEvalItem item in miList)
            {
                TableCell subCell = new TableCell();
                subCell.Text = item.Caption + (item.Type == 1 ? String.Format("({0}分)", item.Param * item.Operator) : "(次)");
                subCell.Style["width"] = "60px";
                subCell.CssClass = "FixedRow";
                subRow.Cells.Add(subCell);
                ParamVal pv = new ParamVal();
                pv.Index = index;
                pv.ItemID = item.RID;
                ParamVals.Add(pv);
                index++;
            }
            row.Cells.Add(cell);
        }
        cell = new TableCell();
        cell.Text = "备注";
        cell.RowSpan = 2;
        cell.CssClass = "FixedRow";
        cell.Style["width"] = "200px";
        row.Cells.Add(cell);
        _tableWidth += 200;
        tblHead.Rows.Add(row);
        tblHead.Rows.Add(subRow);
        tblHead.Style["width"] = _tableWidth + "px";
    }

    /// <summary>
    /// 填充表格内容
    /// </summary>
    protected void BindBodyTable()
    {
        int i = 1;
        int j = 0;
        Hashtable ht = new Hashtable();
        ht.Add("SchoolMark", SchoolMark);
        ht.Add("IsEffect", "1");
        IList<ClsInfo> clsList = Container<IClsInfoLogic>.Instance.FindAll(ht);

        ListSort<ClsInfo> sort = new ListSort<ClsInfo>(clsList, "Grade", true);
        clsList = sort.Sort();

        foreach (ClsInfo info in clsList)
        {
            TableRow row = new TableRow();
            TableCell cellSNo = new TableCell();
            if (j == 0) cellSNo.Style["border-top"] = "0px";
            cellSNo.Text = i + "&nbsp;";
            cellSNo.CssClass = "FixedCol";
            cellSNo.Style["width"] = "40px";
            cellSNo.Style["text-align"] = "right";
            row.Cells.Add(cellSNo);
            i++;

            TableCell cellSName = new TableCell();
            if (j == 0) cellSName.Style["border-top"] = "0px";
            cellSName.Text = "&nbsp;" + info.ClsName;
            cellSName.CssClass = "FixedCol";
            cellSName.Style["width"] = "100px";
            cellSName.Style["text-align"] = "left";
            row.Cells.Add(cellSName);

            IList<ScoreInputClassEntity> sieList = Container<IClassEvalDetailLogic>.Instance.
                GetScoreInputEntityByClass(info.RID, Attribute, _evalDate, SchoolYear, Term, SchoolMark);
            IList<ParamVal> pvList = new List<ParamVal>();
            foreach (ScoreInputClassEntity item in sieList)
            {
                ParamVal pv = new ParamVal();
                pv.ItemID = item.ItemID;
                if (!ParamVals.Contains(pv)) continue;
                ParamVal p = ParamVals[ParamVals.IndexOf(pv)];
                p.Type = item.Type;
                p.Param = item.Param;
                p.Score = item.Score;
                p.Operator = item.Operator;
                pvList.Add(p);
            }
            ListSort<ParamVal> sortt = new ListSort<ParamVal>(pvList, "Index", true);
            pvList = sortt.Sort();
            foreach (ParamVal pv in pvList)
            {
                TableCell subCell = new TableCell();
                if (j == 0) subCell.Style["border-top"] = "0px";

                subCell.Style["width"] = "60px";
                // 计次
                if (pv.Type == 2)
                {
                    // 可编辑状态
                    if (IsModify)
                    {
                        string html = string.Format(ScoreInputNumericHtmlStr, "txt_" + pv.ItemID + "_" + info.RID + "_2", pv.Param == 0 ? "" : pv.Param.ToString(), pv.Score, pv.Operator);
                        subCell.Text = html;
                        subCell.Attributes.Add("onmouseover", "try{mover(this);}catch(e){}");
                        subCell.Attributes.Add("onmouseout", "try{mout(this);}catch(e){}");
                    }
                    else
                    {
                        subCell.Style["text-align"] = "right";
                        subCell.Text = pv.Param == 0 ? "" : pv.Param.ToString();
                    }
                }
                // 计分
                if (pv.Type == 1)
                {
                    // 可编辑状态
                    if (IsModify)
                    {
                        string html = string.Format(ScoreInputScoreHtmlStr, "txt_" + pv.ItemID + "_" + info.RID + "_1", pv.Param == 0 ? "" : pv.Param.ToString(), pv.Score);
                        subCell.Text = html;
                    }
                    else
                    {
                        subCell.Style["text-align"] = "right";
                        subCell.Text = pv.Param == 0 ? "" : pv.Param.ToString();
                    }
                }

                row.Cells.Add(subCell);
            }

            // 备注
            ClassEvalRemark cr = Container<IClassEvalRemarkLogic>.Instance.
                                    GetRemarkByClass(EvalID, info.RID, Attribute, _evalDate, SchoolYear, Term, SchoolMark);
            TableCell cellRemark = new TableCell();
            if (j == 0) cellRemark.Style["border-top"] = "0px";
            string span = "&nbsp;<span id=\"span_{0}\" title=\"{1}\">{2}</span>";
            span = string.Format(span, info.RID, cr == null ? "" : cr.Data, cr == null ? "" : cr.Data.Length > 20 ? cr.Data.Substring(0, 20) + "..." : cr.Data);
            cellRemark.Text = span;
            cellRemark.Attributes.Add("ClassID", info.RID.ToString());
            cellRemark.Attributes.Add("ClassName", info.ClsName);
            if (IsModify) cellRemark.Attributes.Add("onclick", "displayRemark(this)");
            cellRemark.Style["width"] = "200px";
            cellRemark.Style["text-align"] = "left";
            row.Cells.Add(cellRemark);
            tblHead.Rows.Add(row);
            tblHead.Style["width"] = _tableWidth + "px";
        }

    }

    /// <summary>
    /// 保存单据
    /// </summary>
    [WebMethod]
    public static bool SaveClassEvalScore(string jsonStr, int schoolYear, int term, String evalDate, int evalID, int attribute)
    {
        try
        {
            String[] strArr = evalDate.Split(new char[] { '-' });
            if(strArr.Length != 3)
                return false;

            DateTime dt = new DateTime(Convert.ToInt32(strArr[0]), Convert.ToInt32(strArr[1]), Convert.ToInt32(strArr[2]));
            IList<ClassItems> list = ConvertJson(jsonStr);
            IClassEvalSubmitRecordLogic msrLogic = Container<IClassEvalSubmitRecordLogic>.Instance;
            int? syear = schoolYear == -1 ? (int?)null : schoolYear;
            int? sterm = term == -1 ? (int?)null : term;
            return msrLogic.SaveOrUpdateRecord(evalID, list, attribute, dt, syear, sterm, Common.GetUserInfo().UID, SchoolMark);
        }
        catch (Exception)
        {
            throw;
        }
    }

    private static IList<ClassItems> ConvertJson(string jsonStr)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        return jss.Deserialize<IList<ClassItems>>(jsonStr);
    }

    /// <summary>
    /// 导出EXCEL
    /// </summary>
    [WebMethod]
    public static string GetExcel(ExcelTableCell[][] cells)
    {
        string temp_path = HttpContext.Current.Server.MapPath("../../../");
        string save_path = temp_path + "\\download\\" + ExcelFileName + ".xls";
        HttpContext.Current.Session["filepath"] = save_path;
        ExcelUtil.ExcelExport(save_path, "德育报表", 2, 0, cells);
        return "";
    }
}
